package com.agil.photoalbum.web.servlets;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.agil.photoalbum.db.dao.Functions;
import com.agil.photoalbum.db.entities.User;

/**
 * Servlet implementation class for Servlet: SearchServlet
 *
 */
 public class SearchServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
   
    /* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public SearchServlet() {
		super();
	}   	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}  	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String criteria = request.getParameter("criteria");
		request.setAttribute("criteria", criteria);
//		if(null == criteria){
//			request.getRequestDispatcher("/pages/mainPage.jsp").forward(request,
//					response);
//			return;
//		}

		
		
		
		if(request.getParameter("backTo") != null)
		{
			if(request.getParameter("backTo").equals("main"))
			{
				List listOfFoundPictures = Functions.searchPictureByName(criteria.trim());
				request.setAttribute("listOfFoundPictures", listOfFoundPictures);
				request.getRequestDispatcher("/pages/mainPage.jsp").forward(request,
						response);
				//response.sendRedirect("/photo-album/pages/mainPage.jsp");
			}
			else if(request.getParameter("backTo").equals("home"))
			{
				List listOfFoundPictures = Functions.searchPictureByNameForUser((User)request.getSession().getAttribute("user"), criteria.trim());
				request.setAttribute("listOfFoundPictures", listOfFoundPictures);
				request.getRequestDispatcher("/pages/homePage.jsp").forward(request,
						response);
				//response.sendRedirect("/photo-album/pages/homePage.jsp");
			}
		}
		
	}   	  	   
}